#include "iotool.h"
#include <iostream>
#include "stringconv.h"
static char* ReadAll(const char* filename, int* size)
{
	FILE* file = fopen(filename, "rb");
	fseek(file, 0, SEEK_END);
	long lSize = ftell(file);
	fseek(file, 0, SEEK_SET);
	char* buf = new char[lSize];
	fread(buf, lSize, 1, file);
	*size = (int)lSize;
	fclose(file);
	return buf;
}
static int GetFileType(const char* buf)
{
	if (memcmp(buf, "\xEF\xBB\XBF", 3) == 0)
		return 1;//utf_8 with bom
	if (memcmp(buf, "\xFE\xFF", 2) == 0)
		return 2;//utf16_be
	if (memcmp(buf, "\xFF\xFE", 2) == 0)
		return 3;//utf16_le
	return 0;
}
std::u16string IO::LoadTxtFile_ToUtf16(const char* filename)
{
	int size;
	char* buf = ReadAll(filename, &size);
	int type = GetFileType(buf);

	if (type == 0)//ascii
	{
		std::string str(buf, size);
		delete[] buf;
		return StringConv::ToUtf16String(str);
	}
	else if (type == 1)//utf8 with bom
	{
		std::string str(buf + 3, size - 3);
		delete[] buf;
		return StringConv::ToUtf16String(str);
	}
	else
	{
		char16_t* wbuf = (char16_t*)(buf + 2);
		int wsize = (size - 2) / 2;
		if (type == 2)//utf16_be
		{
			for (int i = 0; i < wsize; i++)
			{
				wbuf[i] = ((wbuf[i] & 0xff00) >> 8) | ((wbuf[i] & 0x00ff) << 8);
			}
		}
		std::u16string wstr(wbuf, wsize);
		delete[] buf;
		return wstr;
	}
}
std::string IO::LoadFile_ToUtf8(const char* filename)
{
	int size;
	char* buf = ReadAll(filename, &size);
	int type = GetFileType(buf);

	if (type == 0)//ascii
	{
		std::string str(buf, size);
		delete[] buf;
		return str;
	}
	else if (type == 1)//utf8 with bom
	{
		std::string str(buf + 3, size - 3);
		delete[] buf;
		return str;
	}
	else
	{
		char16_t* wbuf = (char16_t*)(buf + 2);
		int wsize = (size - 2) / 2;
		if (type == 2)//utf16_be
		{
			for (int i = 0; i < wsize; i++)
			{
				wbuf[i] = ((wbuf[i] & 0xff00) >> 8) | ((wbuf[i] & 0x00ff) << 8);
			}
		}
		std::u16string wstr(wbuf, wsize);
		delete[] buf;
		return StringConv::ToUtf8String(wstr);
	}
}